package com.furniture.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.View;

import com.furniture.R;
import com.furniture.Utils;
import com.furniture.sql.Good;
import com.furniture.ui.utils.data.QiNiuUpLoad;
import com.furniture.sql.manage.GoodManage;
import com.furniture.ui.adapter.GoodAdapter;
import com.furniture.ui.adapter.GoodItemAnimator;
import com.furniture.ui.utils.HttpRequest;
import com.furniture.ui.view.GoodContextMenu;
import com.furniture.ui.view.GoodContextMenuManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class MainActivity extends BaseDrawerActivity implements GoodAdapter.OnGoodItemClickListener,
        GoodContextMenu.OnGoodContextMenuItemClickListener {
    private static final int ANIM_DURATION_TOOLBAR = 300;

    private List<Good> mData;

    @Bind(R.id.rvGood)
    RecyclerView rvGood;
    @Bind(R.id.btnCreate)
    FloatingActionButton fabCreate;
    @Bind(R.id.content)
    CoordinatorLayout clContent;

    @Bind(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;

    private GoodAdapter goodAdapter;
    private GoodManage goodManage;

    private boolean pendingIntroAnimation = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupGood();
        new LoadGood(this, true).execute();
    }

    public class LoadGood extends AsyncTask<Void, Void, List<Good>> {

        private Context mContext;
        private boolean isR;

        public LoadGood(Context mContext, boolean isR) {
            this.mContext = mContext;
            this.isR = isR;
        }

        //加载前处理的操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        //异步加载操作在此方法操作
        @Override
        protected List<Good> doInBackground(Void... params) {
            //获取数据库
            goodManage = GoodManage.newInstance(mContext);

            //网络请求获取json文件
            List<Good> list = null;
            if (goodManage.getGoodDaoNum() == 0 || isR) {
                //从七牛下载json文件
//                HttpDownloader downloader = new HttpDownloader();
//                int result = downloader.downFile("http://7xs9ef.com1.z0.glb.clouddn.com/goodList.json", "Furniture/", "goodList.json");
//                Log.e("QiNiuDownload",String.valueOf(result));
                if (mData.isEmpty()) {

                } else {
                    new QiNiuUpLoad("goodList.json", mData);
                }
                try {
                    Gson gson = new Gson();
                    int x = (int) (Math.random() * 1000);
                    String request = HttpRequest.get("http://7xs9ef.com1.z0.glb.clouddn.com/goodList.json?" + x).accept(HttpRequest.CONTENT_TYPE_JSON).body();
                    list = gson.fromJson(request, new TypeToken<List<Good>>() {
                    }.getType());
//                    Log.e("LoadGood", "request    " + request);

                } catch (Exception e) {
                    list = new ArrayList<Good>();
                }
            }
            if (list == null)
                list = new ArrayList<Good>();
            //更新缓存
            for (Good item : list) {
                goodManage.addItem(item);
            }
            //展示信息
            return goodManage.showGoodList();
        }

        //加载结束后的操作
        @Override
        protected void onPostExecute(List<Good> list) {
            super.onPostExecute(list);
//            Log.e("LoadGood", "onPostExecute    " + new Gson().toJson(list));
            goodAdapter.updateItems(list);
            refreshLayout.setRefreshing(false);
        }

        //加载进度
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }

    private void setupGood() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return 300;
            }
        };
        rvGood.setLayoutManager(linearLayoutManager);
        mData = new ArrayList<Good>();
        goodAdapter = new GoodAdapter(this, mData);
        goodAdapter.setOnGoodItemClickListener(this);
        rvGood.setAdapter(goodAdapter);
        rvGood.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                GoodContextMenuManager.getInstance().onScrolled(recyclerView, dx, dy);
            }
        });
        rvGood.setItemAnimator(new GoodItemAnimator());
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new LoadGood(MainActivity.this, true).execute();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        if (pendingIntroAnimation) {
            pendingIntroAnimation = false;
            startIntroAnimation();
        }
        return true;
    }

    /**
     * 创建打开时的菜单动画
     */
    private void startIntroAnimation() {
        int actionbarSize = Utils.dpToPx(56);
        getToolbar().setTranslationY(-actionbarSize);
        getIvLogo().setTranslationY(-actionbarSize);

        getToolbar().animate()
                .translationY(0)
                .setDuration(ANIM_DURATION_TOOLBAR)
                .setStartDelay(300);
        getIvLogo().animate()
                .translationY(0)
                .setDuration(ANIM_DURATION_TOOLBAR)
                .setStartDelay(400);
    }

    /**
     * 评论按钮方法
     * @param v
     * @param position
     */
    @Override
    public void onCommentsClick(View v, int position) {
        final Intent intent = new Intent(this, CommentsActivity.class);
        int[] startingLocation = new int[2];
        v.getLocationOnScreen(startingLocation);
        intent.putExtra(CommentsActivity.ARG_DRAWING_START_LOCATION, startingLocation[1]);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    /**
     * 更多按钮方法
     * @param v
     * @param itemPosition
     */
    @Override
    public void onMoreClick(View v, int itemPosition) {
        GoodContextMenuManager.getInstance().toggleContextMenuFromView(v, itemPosition, this);
    }

    /**
     * 用户头像按钮方法
     * @param v
     */
    @Override
    public void onProfileClick(View v) {
        int[] startingLocation = new int[2];
        v.getLocationOnScreen(startingLocation);
        startingLocation[0] += v.getWidth() / 2;
        UserProfileActivity.startUserProfileFromLocation(startingLocation, this,0);
        overridePendingTransition(0, 0);
    }

    /**
     * 删除当前Item
     * @param goodItem
     */
    @Override
    public void onDeleteClick(int goodItem) {
        final int i = goodItem;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                goodManage.setGoodList(mData);
                goodManage.delete(i);
            }
        };
        new Thread(runnable).start();
        new LoadGood(MainActivity.this, true).execute();
        GoodContextMenuManager.getInstance().hideContextMenu();
    }

//    @Override
//    public void onShareGoodClick(int goodItem) {
//        GoodContextMenuManager.getInstance().hideContextMenu();
//    }

    @Override
    public void onCopyGoodUrlClick(int goodItem) {
        GoodContextMenuManager.getInstance().hideContextMenu();
    }

    @Override
    public void onCancelClick(int goodItem) {
        GoodContextMenuManager.getInstance().hideContextMenu();
    }

    @OnClick(R.id.btnCreate)
    public void onTakePhotoClick() {
        int[] startingLocation = new int[2];
//        fabCreate.getLocationOnScreen(startingLocation);
//        startingLocation[0] += fabCreate.getWidth() / 2;
        TakePhotoActivity.startCameraFromLocation(startingLocation, this);
//        overridePendingTransition(0, 0);
    }

    public void showLikedSnackBar() {
        Snackbar.make(clContent, R.string.publish_like, Snackbar.LENGTH_SHORT).show();
    }

    public void showDisLikedSnackBar() {
        Snackbar.make(clContent,R.string.publish_dislike, Snackbar.LENGTH_SHORT).show();
    }
}